<template>
    <el-dialog v-model="dialogVisible" title='新增品牌' width="400px">
        <div class="dialog-form">
            <div class="form-item">
                <label class="label">
                    *品牌名称:
                    <el-input v-model="form.name" placeholder="请输入品牌名称" />
                </label>
            </div>
        </div>

        <template #footer>
            <el-button @click="dialogVisible = false">关闭</el-button>
            <el-button type="primary" @click="saveBrand" :loading="saving">
                {{ dialogType ? '更新' : '保存' }}
            </el-button>
        </template>
    </el-dialog>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { ref, defineEmits, defineExpose } from 'vue'
import axios from 'axios'

const dialogVisible = ref(false)
const saving = ref(false)

// 表单数据
const form = ref({ id: '', name: '' })


// 打开新增弹窗
const openAddDialog = async () => {
    dialogVisible.value = true
    form.value = { id: '', name: '' }
}

// 保存品牌
const saveBrand = async () => {

    try {
        saving.value = true

        if (!form.value.name.trim()) {
            ElMessage.error('请输入品牌名称')
            return
        }

        const res = await axios.post('/api/basic/goods/addBrand', form.value)
        if (res.data.code === 5200) {
            ElMessage.success(res.data.msg)
            dialogVisible.value = false
            // 触发成功事件，让父组件重新获取数据
            emit('success')
        } else {
            ElMessage.error(res.data.msg)
        }
    } catch (error) {
        ElMessage.error(error.message)
    } finally {
        saving.value = false
    }
}

const emit = defineEmits(['success'])

defineExpose({
    openAddDialog
})
</script>